const { defineConfig } = require("@vue/cli-service");
// 项目组件的按需引入
const { VantResolver } = require("unplugin-vue-components/resolvers");
const ComponentsPlugin = require("unplugin-vue-components/webpack");

// 解析post传来的参数
const BodyParser = require('body-parser');

const Mock = require('mockjs')

const jwt = require('jsonwebtoken')

// 用户列表
const userList = [
  {
    username: 'admin',
    password: '123',
    name: '张三',
    id: "1",
    img: Mock.mock("@image(100x100, @color)")
  },
  {
    username: 'user',
    password: '456',
    name: '李四',
    id: "2",
    img: Mock.mock("@image(100x100, @color)")
  }
]

// 数据列表
const list = Mock.mock({
  "list|100-200": [
    {
      img: "@image(100x100,@color)",
      title: "@title",
      id: "@id",
      "price|100-200":1,
    }
  ]
})

module.exports = defineConfig({
  transpileDependencies: true,

  // 项目组件的按需引入配置
  configureWebpack: {
    plugins: [
      ComponentsPlugin({
        resolvers: [VantResolver()],
      }),
    ],
  },

  // 服务拦截器
  devServer: {
    onBeforeSetupMiddleware: ({app}) => {
      app.use(BodyParser.json());


      // 登录接口
      app.post('/api/login', (req, res) => {
        // 获取前端传来的参数
        const { username, password } = req.body;

        const data = userList.find(item => item.username === username && item.password === password)

        if(data) {
          res.send({
            code: 1,
            token: jwt.sign(data.id, '2210A'),
            msg: '登录成功'
          })
        } else {
          res.status(403)

          res.send({
            code: 0,
            msg: '登录失败，用户名或者密码错误'
          })
        }
      })

      // 列表接口
      app.post('/api/getList', (req, res) => {
        // 获取前端传来的数据
        const { size, current, search } = req.body;

        // 记录数据
        let newList = list.list;

        // 记录数据长度
        let total = newList.length

        if(search) {
          newList = newList.filter(item => item.title.indexOf(search) !== -1)

          total = newList.length
        }

        newList = newList.filter((item, idx) => {
          return idx < size * current
        })
        

        res.send({
          code: 1,
          data: newList,
          total: total
        })
      })
    }
  }
});
